package com.lagou.service.impl;

import com.lagou.dao.CodeDao;
import com.lagou.pojo.LagouAuthCode;
import com.lagou.service.CodeService;
import com.lagou.service.EmailService;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.util.CollectionUtils;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private CodeDao codeDao;

    //@Autowired
    //private EmailClient emailClient;
    //spring cloud dubbo远程调用
    @Reference
    private EmailService emailService;

    @Override
    public Boolean create(String email) {
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            int nextInt = ThreadLocalRandom.current().nextInt(9);
            code.append(nextInt);
        }
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setCode(code.toString());
        lagouAuthCode.setEmail(email);
        Date date = new Date();
        lagouAuthCode.setCreatetime(date);
        //过期时间为十分钟
        lagouAuthCode.setExpiretime(new Date(date.getTime() + 60000));
        LagouAuthCode save = codeDao.save(lagouAuthCode);
        //远程调用email服务发送邮件
        Boolean isSend = emailService.send(email, code.toString());
        return isSend && save.getId() != null;
    }

    @Override
    public Integer validate(String email, String code) {
        //0正确1错误2超时
        if (StringUtils.isBlank(email) || StringUtils.isBlank(code)) {
            return 1;
        }
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setCode(code);
        lagouAuthCode.setEmail(email);
        Example<LagouAuthCode> example = Example.of(lagouAuthCode);
        List<LagouAuthCode> lagouAuthCodes = codeDao.findAll(example);
        //没有匹配到数据
        if (CollectionUtils.isEmpty(lagouAuthCodes)) {
            return 1;
        }
        Date now = new Date();
        LagouAuthCode lagouAuthCodeTime = lagouAuthCodes.stream().sorted(Comparator.comparing(LagouAuthCode::getExpiretime).reversed()).findFirst().get();
        //超时
        if (now.getTime() > lagouAuthCodeTime.getExpiretime().getTime()) {
            return 2;
        }
        return 0;
    }

}
